package enduringLink.call;

import data.handle.Result;
import enduringLink.MyProxy;
import enduringLink.RequestHandler;
import instance.LocalInstance;
import io.netty.channel.Channel;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

//查询结果传输对象，用于在RPC调用中传输每个实例的查询结果
public class MyTransfer implements Transfer {

    //负责收集查询结果的队列
    private LinkedBlockingQueue<Result> results = new LinkedBlockingQueue<>();
    //零件销量对象
    private MyQuantityHandle myQuantityHandle;

    private CountDownLatch countDownLatch;

    public MyTransfer(MyQuantityHandle myQuantityHandle){
        this.myQuantityHandle = myQuantityHandle;
    }

    //用于控制实例调用，远程实例实现，收集指定品牌的查询结果
    @Override
    public void get(byte brandIndex) {
        Channel channel = RequestHandler.getChannel();
        MyProxy myProxy = new MyProxy(channel);
        Transfer transfer = myProxy.proxyGet(Transfer.class);
        double avgQuantity = myQuantityHandle.getTotalQuantity() / 2000000;
        //获得当前实例的查询结果
        LinkedBlockingQueue<Result> results = LocalInstance.getResult(brandIndex, avgQuantity * 0.3);
        System.out.println("brandIndex : " + brandIndex + " results :" + results);
        transfer.transferData(results);
    }

    //用于远程实例调用，控制实例实现，汇总指定品牌的查询结果
    @Override
    public void transferData(LinkedBlockingQueue<Result> res) {

        for (Result re : res) {
            results.add(re);
        }
        countDownLatch.countDown();

    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public LinkedBlockingQueue<Result> getResults() {
        return results;
    }

}
